package com.yenlien.traceyun.milk.service;

import com.yenlien.traceyun.milk.dao.FarmersDao;
import com.yenlien.traceyun.milk.dao.StorageDao;
import com.yenlien.traceyun.milk.entity.Storage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Date 2022/7/11
 * @Author jiaLong
 * @Descript
 */
@Service
public class StorageService {

    @Autowired
    private StorageDao storageDao;

    public Storage save(Storage storage) {
        storage.setInTime(new Date());
        return storageDao.save(storage);
    }

    public Page<Storage> findByList(Storage storage) {
        Pageable pageable = PageRequest.of(storage.getPage(), storage.getPageSize(), Sort.Direction.DESC, "createtime");
        return storageDao.findAll((Root<Storage> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (!StringUtils.isEmpty(storage.getCompanyId())) {
                list.add(cb.equal(root.get("companyId"), storage.getCompanyId()));
            }
            if (!StringUtils.isEmpty(storage.getIdentifier())) {
                list.add(cb.equal(root.get("identifier"), storage.getIdentifier()));
            }
            if (!StringUtils.isEmpty(storage.getFarmersName())) {
                list.add(cb.like(root.get("farmersName"), "%" + storage.getFarmersName() + "%"));
            }
            if (!StringUtils.isEmpty(storage.getPastureName())) {
                list.add(cb.like(root.get("pastureName"), "%" + storage.getPastureName() + "%"));
            }
            Predicate[] predicate = new Predicate[list.size()];
            return cb.and(list.toArray(predicate));
        }, pageable);
    }

}
